package com.example.ws.config;
import com.example.ws.WsMessageListenerCallBack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import static com.example.common.constant.SystemConstant.MessageChannelNamePrefix;

@Configuration
public class RedisPubSubConfig {

    @Autowired
    private InetUtils inetUtils;

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {


        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);

        /**
         *   可以添加多个 messageListener，配置不同的交换机
         *   应该从配置文件中读取
         */
        String host = inetUtils.findFirstNonLoopbackAddress().getHostAddress();

        /**
         * 订阅
         */
        container.addMessageListener(listenerAdapter, new PatternTopic(MessageChannelNamePrefix + host));

        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(WsMessageListenerCallBack receiver) {

        return new MessageListenerAdapter(receiver, "onMessage");
    }

}
